package hot.job.autoconfigure;

import hot.job.autoconfigure.runner.HotJobRunner;
import hot.job.core.factory.AutowireCapableJobFactory;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * hot job autoconfiguration
 *
 * @author gaowenhao
 * @since 2022/7/5 15:13
 */
@Configuration
@ConditionalOnClass({SchedulerFactoryBean.class, Scheduler.class, HotJobRunner.class})
public class HotJobAutoConfiguration {


    @Bean
    @ConditionalOnMissingBean(AutowireCapableJobFactory.class)
    public AutowireCapableJobFactory autowireCapableJobFactory(AutowireCapableBeanFactory autowireCapableBeanFactory){
        return new AutowireCapableJobFactory(autowireCapableBeanFactory);
    }


    @Bean
    @ConditionalOnMissingBean(SchedulerFactoryBean.class)
    public SchedulerFactoryBean schedulerFactoryBean(AutowireCapableJobFactory autowireCapableJobFactory){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setJobFactory(autowireCapableJobFactory);
        return schedulerFactoryBean;
    }


    @Bean
    @ConditionalOnMissingBean(Scheduler.class)
    public Scheduler scheduler(SchedulerFactoryBean schedulerFactoryBean) throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        scheduler.start();
        return scheduler;
    }


    @Bean
    @ConditionalOnMissingBean(HotJobRunner.class)
    public HotJobRunner hotJobRunner(){
        return new HotJobRunner();
    }


}
